package chapter29;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;

public class ProgressBarDemo extends JFrame{
	
	private JProgressBar jpb = new JProgressBar();
	private JTextArea jtaResult = new JTextArea();
	private JTextField jtfPrimeCount = new JTextField(8);
	private JButton jbtDisplayPrime = new JButton("Display Prime");
	
	public ProgressBarDemo(){
		jpb.setStringPainted(true);
		jpb.setValue(0);
		jpb.setMaximum(100);
		
		jtaResult.setWrapStyleWord(true);
		jtaResult.setLineWrap(true);
		
		JPanel panel = new JPanel();
		panel.add(new JLabel("Enter the prime number count"));
		panel.add(jtfPrimeCount);
		panel.add(jbtDisplayPrime);
		
		add(jpb, BorderLayout.NORTH);
		add(new JScrollPane(jtaResult), BorderLayout.CENTER);
		add(panel, BorderLayout.SOUTH);
		
		jbtDisplayPrime.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				jtaResult.setText("");
				ComputePrime task = new ComputePrime(
						Integer.parseInt(jtfPrimeCount.getText()), jtaResult);
				task.addPropertyChangeListener(new PropertyChangeListener() {
					
					@Override
					public void propertyChange(PropertyChangeEvent arg0) {
						// TODO Auto-generated method stub
						if ("progress".equals(arg0.getPropertyName())) {
							jpb.setValue((Integer) arg0.getNewValue());//获取第87行的进度值
						}
					}
				});
				
				task.execute();
			}
		});
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ProgressBarDemo frame = new ProgressBarDemo();
		frame.setTitle("ProgressBarDemo");
		frame.setSize(500, 150);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
	
	static class ComputePrime extends SwingWorker<Integer, Integer> {
		private int count;
		private JTextArea result;
		
		public ComputePrime(int count, JTextArea result){
			this.count = count;
			this.result = result;
		}
		
		protected Integer doInBackground(){
			publishPrimeNumbers(count);
			return 0;
		}
		
//		protected void process(ArrayList<Integer> list){
//			for (int i = 0; i < list.size(); i++) {
//				result.append(list.get(i) + " ");
//			}
//		}
		
		public void publishPrimeNumbers(int n){
			int count = 0;
			int number = 2;
			while (count <= n){
				if (isPrime(number)){
					count++;
					setProgress(100 * count / n);
					result.append(number + " ");
//					publish(number);
				}
				number++;
			}
		}
		
		private static boolean isPrime(int number){
			for (int divisor = 2; divisor <= number / 2; divisor++){
				if (number % divisor == 0){
					return false;
				}
			}
			return true;
		}
	}

}
